# -*- coding: utf-8 -*-
import os
import time
import string
from xml.dom import minidom
from BeautifulSoup import BeautifulStoneSoup
from django.conf import settings
from django.core.files.uploadedfile import UploadedFile

def get_messages(filename, clear=False):
    return Messaging(filename=filename).get(remove=clear)

def set_messages(filename, messages):
    return Messaging(filename=filename).set(messages=messages)

def get_msgfile(request):
    if request.session.has_key('msg_file'):
        return request.session['msg_file']
    else:
        return os.path.join(settings.MSG_DIR, '%s.msg' % (time.time()))

def make_dirs(title):
    try:
        folder_name = Transliterator.cleancyrillic(text=title)
        program_path = os.path.join(settings.MEDIA_ROOT, folder_name)
        os.makedirs(program_path, 0775)

        for folder in ['picture', 'video', 'document', 'audio', 'other']:
            os.makedirs(os.path.join(program_path, folder), 0775)
        return True
    except IOError:
        return False

class Transliterator:
    conversion = {
        u' ': ' ', u'0': '0', u'1': '1', u'2': '2', u'3': '3', u'4': '4', u'5': '5',
        u'6': '6', u'7': '7', u'8': '8', u'9': '9', u'а': 'a', u'б': 'b', u'в': 'v',
        u'г': 'g', u'д': 'd', u'е': 'e', u'ё': 'e', u'ж': 'zh', u'з': 'z', u'и': 'i',
        u'й': 'j', u'к': 'k', u'л': 'l', u'м': 'm', u'н': 'n', u'о': 'o', u'п': 'p',
        u'р': 'r', u'с': 's', u'т': 't', u'у': 'u', u'ф': 'f', u'х': 'h', u'ц': 'c',
        u'ч': 'ch', u'ш': 'sh', u'щ': 'sch', u'ы': 'y', u'ь': '_', u'э': 'e', u'ю': 'ju',
        u'я': 'ja', 'ъ': '_',
        u'А': 'A', u'Б': 'B', u'В': 'V', u'Г': 'G', u'Д': 'D', u'Е': 'E', u'Ё': 'E',
        u'Ж': 'ZH', u'З': 'Z', u'И': 'I', u'Й': 'J', u'К': 'K', u'Л': 'L', u'М': 'M',
        u'Н': 'N', u'О': 'O', u'П': 'P', u'Р': 'R', u'С': 'S', u'Т': 'T', u'У': 'U',
        u'Ф': 'F', u'Х': 'H', u'Ц': 'C', u'Ч': 'CH', u'Ш': 'SH', u'Щ': 'SCH', u'Ь': '_',
        u'Ы': 'Y', u'Ъ': '_', u'Э': 'E', u'Ю': 'JU', u'Я': 'JA',
        u',': '-',
        }

    @classmethod
    def cyr2lat(cls, s):
        retval = []
        for c in s:
            if ord(c) > 128:
                try:
                    c = cls.conversion[c]
                except KeyError:
                    c = ''
                retval.append(c)

        return ''.join(retval)

    @classmethod
    def cleancyrillic(cls, text):
        """
        Clean cyrillic text, replace spaces with -,
        cyrillic text with transliterated
        """
        text = text.replace(' ', '-')
        for char in text:
            if cls.conversion.has_key(char):
                text = text.replace(char, cls.conversion.get(char))
        return text

class Messaging:
    """ Provides view to view message passing
        in the following format
        {
            'type': 'message type',
            'message': 'message body'
        }
    """
    def __init__(self, filename):
        self.filename = filename

    def get(self, remove=False):
        """ Returns messages as dictionary
            @param remove message file when reading done or not
        """
        if os.path.exists(self.filename):
            return self._read(remove=remove)
        return None

    def set(self, messages):
        """ Returns messages as dictionary """
        return self._write(messages=messages)

    def _read(self, remove=False):
        """ Creates dictionary with the following structure
            @returns list<dict> {
                'type': 'message type',
                'message': 'message body'
            }
        """
        messages = []
        try:
            messagefile = open(self.filename, 'r')
            soup = BeautifulStoneSoup(''.join(messagefile.readlines()))

            if soup.find('messages') is None: return None

            for message in soup.findAll('message'):
                messages.append({
                    'type': message['type'],
                    'message': message.string
                })

            if remove:
                os.unlink(self.filename)

            return messages
        except IOError:
            return None

    def _write(self, messages):
        try:
            doc = minidom.Document()
            rootNode = doc.createElement('messages')
            doc.appendChild(rootNode)

            for message in messages:
                msgTag = doc.createElement('message')
                msgTag.setAttribute('type', message['type'])
                msgTag.appendChild(doc.createTextNode(message['message']))

                rootNode.appendChild(msgTag)

            messagefile = open(self.filename, 'w')
            doc.writexml(writer=messagefile)
            messagefile.close()

            return True
        except IOError:
            return False

class UploadManager(UploadedFile):
    pass
